package com.gly091020.client;

import com.gly091020.ChineseChest;
import com.gly091020.ChineseChestFun;
import com.gly091020.ChineseChestFun.Poem;
import com.gly091020.util.ChineseChestNetworkID;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.regex.Pattern;

public class PoemFillScreen extends Screen {

    private static final Pattern CHINESE_CHAR_PATTERN = Pattern.compile("[\\u4e00-\\u9fa5]");
    private final Poem poem;
    private final List<TextFieldWidget> blankFields = new ArrayList<>();
    private final Map<TextFieldWidget, String> correctAnswers = new HashMap<>();
    private final List<LineSegment> lineSegments = new ArrayList<>();
    private int startY;
    private final BlockPos pos;
    private final long seed;

    public PoemFillScreen(Poem poem, BlockPos p, long s) {
        super(Text.of("古诗填空"));
        this.poem = poem;
        this.pos = p;
        this.seed = s;
    }

    @Override
    protected void init() {
        super.init();
        blankFields.clear();
        correctAnswers.clear();
        lineSegments.clear();
        startY = 20;
        net.minecraft.util.math.random.Random r = net.minecraft.util.math.random.Random.create();
        r.setSeed(seed);

        // 添加标题和作者
        lineSegments.add(new TextSegment(poem.title, width / 2 - textRenderer.getWidth(poem.title) / 2, startY));
        startY += textRenderer.fontHeight;
        lineSegments.add(new TextSegment(poem.writer, width / 2 - textRenderer.getWidth(poem.writer) / 2, startY));
        startY += (int) (textRenderer.fontHeight * 1.5);

        // 处理诗句
        for (int i = 0; i < poem.sentences.size(); i++) {
            String sentence = poem.sentences.get(i);

            // 统计逗号数量
            int commaCount = 0;
            for (char c : sentence.toCharArray()) {
                if (c == '，' || c == '、') {
                    commaCount++;
                }
            }

            // 计算需要挖空的数量 (逗号数量+1)
            int blankCount = commaCount + 1;

            List<Integer> validIndices = new ArrayList<>();
            // 收集有效汉字的位置
            for (int j = 0; j < sentence.length(); j++) {
                String ch = String.valueOf(sentence.charAt(j));
                if (CHINESE_CHAR_PATTERN.matcher(ch).matches()) {
                    validIndices.add(j);
                }
            }

            if (validIndices.isEmpty() || blankCount == 0) {
                // 直接显示整句
                lineSegments.add(new TextSegment(sentence, width / 2 - textRenderer.getWidth(sentence) / 2, startY));
                startY += textRenderer.fontHeight;
                continue;
            }

            // 随机选择要隐藏的字（数量为blankCount）
            Collections.shuffle(validIndices, new Random(r.nextLong()));
            List<Integer> hiddenIndices = validIndices.subList(0, Math.min(blankCount, validIndices.size()));
            Collections.sort(hiddenIndices); // 按位置排序

            // 计算整句宽度（用于居中）
            int sentenceWidth = textRenderer.getWidth(sentence);
            int currentX = width / 2 - sentenceWidth / 2;
            // 当前处理的字符索引

            // 遍历句子字符
            for (int j = 0; j < sentence.length(); j++) {
                String currentChar = String.valueOf(sentence.charAt(j));
                int charWidth = textRenderer.getWidth(currentChar);

                if (hiddenIndices.contains(j)) {
                    // 创建填空
                    TextFieldWidget blankField = getTextFieldWidget(currentX, charWidth);

                    this.addDrawableChild(blankField);
                    blankFields.add(blankField);
                    correctAnswers.put(blankField, currentChar);

                    currentX += charWidth;
                } else {
                    // 添加普通文本
                    StringBuilder segment = new StringBuilder();

                    // 收集连续的非隐藏字符
                    while (j < sentence.length() && !hiddenIndices.contains(j)) {
                        segment.append(sentence.charAt(j));
                        j++;
                    }
                    j--; // 回退一步

                    int segmentWidth = textRenderer.getWidth(segment.toString());
                    lineSegments.add(new TextSegment(segment.toString(), currentX, startY));
                    currentX += segmentWidth;
                }
            }

            startY += textRenderer.fontHeight;
        }

        // 添加提交按钮
        this.addDrawableChild(ButtonWidget.builder(Text.translatable("gui.chinese_chest.ok"), button -> checkAnswers())
                .dimensions(width / 2 - 50, startY + 10, 100, 20).build());

        if(ChineseChest.config.glyMode && ChineseChestFun.isGLY()){
            for(TextFieldWidget widget: blankFields){
                widget.setText(correctAnswers.get(widget));
            }
        }
    }

    private @NotNull TextFieldWidget getTextFieldWidget(int currentX, int charWidth) {
        TextFieldWidget blankField = new TextFieldWidget(
                textRenderer,
                currentX,
                startY, // 微调垂直位置
                charWidth + 8, // 增加一点宽度
                textRenderer.fontHeight,
                Text.of("")
        );
        blankField.setMaxLength(1);
        blankField.setEditable(true);
        blankField.setDrawsBackground(false);
        return blankField;
    }

    @Override
    public void render(DrawContext context, int mouseX, int mouseY, float delta) {
        renderBackground(context);
        super.render(context, mouseX, mouseY, delta);

        // 渲染所有文本段
        for (LineSegment segment : lineSegments) {
            segment.render(context, textRenderer);
        }

        // 绘制输入框下划线
        for (TextFieldWidget widget : blankFields) {
            int underlineY = widget.getY() + widget.getHeight() - 1;
            context.drawBorder(widget.getX(), underlineY, textRenderer.getWidth("我") - 1,
                    1, 0xFFFFFFFF);
        }
    }

    private void checkAnswers() {
        int correctCount = 0;
        for (TextFieldWidget field : blankFields) {
            if (correctAnswers.get(field).equals(field.getText())) {
                correctCount++;
            }
        }
        float correctRatio = blankFields.isEmpty() ? 1.0f : (float) correctCount / blankFields.size();
        sendAnswer(correctRatio);
    }

    @Override
    public boolean shouldCloseOnEsc() {
        return false;
    }

    // 文本段基类
    private interface LineSegment {
        void render(DrawContext context, net.minecraft.client.font.TextRenderer renderer);
    }

    // 纯文本段
    private record TextSegment(String text, int x, int y) implements LineSegment {
        @Override
        public void render(DrawContext context, net.minecraft.client.font.TextRenderer renderer) {
            context.drawText(renderer, text, x, y, 0xFFFFFF, true);
        }
    }

    // 打开界面的工具方法
    public static void open(Poem poem, BlockPos p, long s) {
        MinecraftClient.getInstance().setScreen(new PoemFillScreen(poem, p, s));
    }

    public void sendAnswer(float correctRatio){
        var p = PacketByteBufs.create();
        p.writeBlockPos(pos);
        p.writeLong(seed);
        p.writeFloat(correctRatio);
        ClientPlayNetworking.send(ChineseChestNetworkID.SEND_ANSWER, p);
        this.close();
    }
}